package com.bonc.tools;

import com.bonc.data.service.impl.DataLoadServiceImpl;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.*;

/**
 * Created by zhangxinsong on 2019-03-27.
 */
public class FolderFileScanner {
    private static final Logger logger = Logger.getLogger(FolderFileScanner.class);

    /**
     * 递归扫描指定文件夹下面的指定文件
     *
     * @return ArrayList<Object>
     * @author
     * @time 2017年11月3日
     */
    public static ArrayList<String> scanFilesWithRecursion(String folderPath) throws Exception {
        ArrayList<String> dirctorys = new ArrayList<String>();
        ArrayList<String> scanFiles = new ArrayList<String>();
        File directory = new File(folderPath);
        if (!directory.isDirectory()) {
            throw new Exception('"' + folderPath + '"' + " input path is not a Directory , please input the right path of the Directory. ^_^...^_^");
        }
        if (directory.isDirectory()) {
            File[] filelist = directory.listFiles();
            for (int i = 0; i < filelist.length; i++) {
                /**如果当前是文件夹，进入递归扫描文件夹**/
                if (filelist[i].isDirectory()) {
                    //绝对路径名字符串
                    dirctorys.add(filelist[i].getAbsolutePath());
                    /**递归扫描下面的文件夹**/
                    scanFilesWithRecursion(filelist[i].getAbsolutePath());
                }
                /**非文件夹**/
                else {
                    scanFiles.add(filelist[i].getAbsolutePath());
                }
            }
        }
        return scanFiles;
    }

    /**
     * 扫描固定文件夹下的指定文件
     */
    public static ArrayList<File> getFiles(String folderPath) throws Exception {
        ArrayList<File> scanFiles = new ArrayList<>();
        File directory = new File(folderPath);
        if (!directory.isDirectory()) {
            throw new Exception('"' + folderPath + '"' + " input path is not a Directory , please input the right path of the Directory. ^_^...^_^");
        } else {
            //首先将第一层目录扫描一遍
            File[] files = directory.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    String path = files[i].getAbsolutePath();
                    if (path.endsWith(".txt")) {
                        scanFiles.add(files[i]);
                        logger.info(files[i].getAbsolutePath());
                    }
                }
            }
        }
        return scanFiles;
    }

    /**
     * 非递归方式扫描指定文件夹下面的所有文件
     *
     * @param folderPath 需要进行文件扫描的文件夹路径
     * @return ArrayList<Object>
     * @author
     * @time 2017年11月3日
     */
    public static ArrayList<String> scanFilesWithNoRecursion(String folderPath) throws Exception {
        ArrayList<String> scanFiles = new ArrayList<String>();
        LinkedList<File> queueFiles = new LinkedList<File>();
        File directory = new File(folderPath);
        if (!directory.isDirectory()) {
            throw new Exception('"' + folderPath + '"' + " input path is not a Directory , please input the right path of the Directory. ^_^...^_^");
        } else {
            //首先将第一层目录扫描一遍
            File[] files = directory.listFiles();
            //遍历扫出的文件数组，如果是文件夹，将其放入到linkedList中稍后处理
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    queueFiles.add(files[i]);
                } else {
                    //暂时将文件名放入scanFiles中
                    scanFiles.add(files[i].getAbsolutePath());
                }
            }

            //如果linkedList非空遍历linkedList
            while (!queueFiles.isEmpty()) {
                //移出linkedList中的第一个
                File headDirectory = queueFiles.removeFirst();
                File[] currentFiles = headDirectory.listFiles();
                for (int j = 0; j < currentFiles.length; j++) {
                    if (currentFiles[j].isDirectory()) {
                        //如果仍然是文件夹，将其放入linkedList中
                        queueFiles.add(currentFiles[j]);
                    } else {
                        scanFiles.add(currentFiles[j].getAbsolutePath());
                    }
                }
            }
        }

        return scanFiles;
    }

    /*
     * Java文件操作 获取文件扩展名
     *
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /*
     * Java文件操作 获取不带扩展名的文件名
     *
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    public static void main(String[] args) {

        String folderPath = "D:/江西/新建文件夹";//扫描的路径
        ArrayList<File> files;//该路径下的文件列表，只取一层
        HashMap<String, List<String>> fields = new HashMap();//文件名信息（用途，时间，条数）
        HashMap<String, List<String>> columns = new HashMap();//根据文件头信息创建表结构列名
        try {
            files = getFiles(folderPath);
            for (File file : files) {
                String noEx = file.getName().split("\\.")[0];
                List<String> far = new ArrayList<>();
                Collections.addAll(far, noEx.split("_"));
                String type = far.get(0);
                far.remove(0);
                fields.put(noEx, far);


                long lineCount = ReadFromFile.getFileLineCount(file);
                logger.info(lineCount);


                String tempString = ReadFromFile.getFirstLine(file);
                if (tempString != null) {
                    List<String> car = new ArrayList<>();
                    Collections.addAll(car, tempString.split("\\|"));
                    columns.put(noEx, car);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}